<template>
  <div class="view_page " style="height: calc(100% - 20px)">
    <el-card class="box-card monitor-setting-card" style="height: 100%;">
      <!--卡片头部-->
      <div slot="header" class="clearfix">
        <!--左侧-->
        <div class="left">
          <div class="menu-title">
            监测分析
          </div>
        </div>
      </div>
      <!-- 卡片内容 -->
      <div class="card-container">
        <el-row :gutter="16" style="height: 100%;">
          <el-col :span="3">
            <div class="river-type-select-div box-sizing">
              <div class="river-type-select-item"
                   v-for="(item,index) in typeList" :key="index"
                   @click="handleRiverTypeClick(item,index)"
                   :class="{'active':item.id==currentType}"
              >{{ item.name }}
              </div>
            </div>
          </el-col>
<!--          <el-col :span="currentType==-1?0:4">
            <div class="river-type-select-div box-sizing">
              <div class="river-type-select-item"
                   v-for="(item,index) in ((allDataList[currentTypeIndex-1]&&allDataList[currentTypeIndex-1].children)?allDataList[currentTypeIndex-1].children:[])"
                   :key="index"
                   @click="handleSubRiverListClick(item)"
                   :class="{'active':(item.id==currentSubRiverId)}">
                {{ item.name }}
              </div>
            </div>
          </el-col>-->
          <el-col :span="21">
            <div>
              <div class="state-list-div">
                <div class="state-item" v-for="(item,index) in stateList"
                     :key="index" @click="handleStateClick(item)"
                     :class="{'active':item.id==currentState}"
                     v-if="item.isShow">
                  {{ item.name }}
                </div>
              </div>
              <div class="state-normal-div"
                   v-if="monitorStateIds.indexOf(currentState)>-1">
                <div class="setting-div">
                  <div class="right">
                    <el-button type="primary" size="small"
                               @click="navtoAdd('add')">新增分组
                    </el-button>
                  </div>
                </div>
                <el-table :data="datalist" style="width: 100%" ref="myTable">
                  <el-table-column v-for="(item,ind) in tableList" :key="ind"
                                   :label="item.label"
                                   :prop="item.key" :align="item.align"
                                   :min-width="item.minWidth">
                    <template slot-scope="scope">
                      <div v-if="!item.isCustom" class="text-ellipsis-2">
                        {{ scope.row[item.key] || item.defaultText }}
                      </div>
                      <div class="text-ellipsis-2"
                           v-if="item.isCustom&&item.key!='ind'">
                        {{ scope.row[item.key] || item.defaultText }}
                      </div>
                      <div class="text-ellipsis-2"
                           v-if="item.isCustom&&item.key=='ind'">
                        {{ (scope.$index + 1) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="测点列表"
                                   min-width="110"
                                   align="center">
                    <template slot-scope="scope">
                      <el-button type="primary" size="small"
                                 @click="tipLookMonitorList(scope.row)">点击查看
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" min-width="216"
                                   align="center">
                    <template slot-scope="scope">
                      <el-button type="success" size="small"
                                 @click="navtoAdd('query',scope.row)">详情
                      </el-button>
                      <el-button type="primary" size="small"
                                 @click="navtoAdd('update',scope.row)">修改
                      </el-button>
                      <el-button type="danger" size="small"
                                 @click="del(scope.row)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="state-device-div"
                   v-if="deviceStateIds.indexOf(currentState)>-1||siteStateIds.indexOf(currentState)>-1">
                <!--                <div class="setting-div">
                                  <div class="left">
                                    <el-select v-if="deviceStateIds.indexOf(currentState)>-1"
                                               v-model="currentDeviceId">
                                      <el-option v-for="(item,di) in deviceList" :key="1000+di"
                                                 v-if="item&&item.id"
                                                 :label="item.name" :value="item.id">
                                      </el-option>
                                    </el-select>
                                    <el-select v-if="siteStateIds.indexOf(currentState)>-1"
                                               v-model="currentSiteId">
                                      <el-option v-for="(item,si) in siteList" :key="10000+si"
                                                 v-if="item&&item.id"
                                                 :label="item.name" :value="item.id">
                                      </el-option>
                                    </el-select>
                                  </div>
                                  <div class="right">
                                    <el-button type="primary" size="small"
                                               v-if="deviceStateIds.indexOf(currentState)>-1"
                                               :disabled="currentDeviceUpdateType=='add'"
                                               @click="resetDeviceSetting">恢复默认
                                    </el-button>
                                    <el-button type="primary" size="small"
                                               :disabled="(currentType==4&&deviceSetList.length==0)||(currentState==5&&siteList.length==0)"
                                               @click="updateDeviceSetting">更新配置
                                    </el-button>
                                  </div>
                                </div>-->
                <el-table :data="deviceSetList" style="width: 100%"
                          ref="deviceSetTable">
                  <el-table-column v-for="(item,ind) in deviceDefaultTableList"
                                   :key="ind"
                                   :label="item.label"
                                   :prop="item.key" :align="item.align"
                                   :min-width="item.minWidth">
                    <template slot-scope="scope">
                      <div v-if="!item.isCustom" class="text-ellipsis-2">
                        {{ scope.row[item.key] || item.defaultText }}
                      </div>
                      <div class="text-ellipsis-2"
                           v-if="item.isCustom&&item.key!='ind'">
                        {{ scope.row[item.key] || item.defaultText }}
                      </div>
                      <div class="text-ellipsis-2"
                           v-if="item.isCustom&&item.key=='ind'">
                        {{ (scope.$index + 1) }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import {Message} from "element-ui";
// import pagination from "@/components/common/pagination/pagination";

export default {
  name: 'monitorGroup',
  components: {
    // pagination,
  },
  data() {
    return {
      token: "",
      userInfo: JSON.parse(localStorage.getItem("loginPersonnelInformation")),
      // 选择状态
      currentStateIndex: 0,
      currentState: 1,
      monitorStateIds: [1, 2, 3],
      deviceStateIds: [4],
      siteStateIds: [5],
      stateList: [
        {
          id: 1,
          name: "实时状态",
          isShow: true,
        },
        {
          id: 2,
          name: "实时监测",
          isShow: true,
        },
        {
          id: 3,
          name: "安全监测",
          isShow: true,
        },
        // {
        //   id: 4,
        //   name: "设备监测信息",
        //   isShow: false,
        // },
        // {
        //   id: 5,
        //   name: "站点监测信息",
        //   isShow: false,
        // },
      ],
      currentType: -1,
      currentTypeIndex: 0,
      typeList: [
        {
          id: -1,
          name: "全局"
        },
        {
          id: 1,
          name: "马河水库"
        },
        {
          id: 2,
          name: "户主水库"
        },
      ],

      // TODO.全局
      tableList: [
        {
          key: 'ind',
          label: '序号',
          align: 'center',
          minWidth: '100',
          defaultText: '--',
          isCustom: true,
        },
        {
          key: 'name',
          label: '分组名称',
          align: 'center',
          minWidth: '120',
          defaultText: '--',
          isCustom: false,
        },
      ],
      datalist: [],
      pageNum: 1,
      page: 1,
      size: 10,
      total: 0,
      currentSubRiverId: -1,
      // 设备列表
      allDataList: [],
      deviceList: [],
      currentDeviceId: '',
      currentDeviceUpdateType: 'add',
      deviceSetList: [],
      deviceDefaultTableList: [
        {
          key: 'ind',
          label: '序号',
          align: 'center',
          minWidth: '100',
          defaultText: '--',
          isCustom: true,
        },
        {
          key: 'name',
          label: '测点名称',
          align: 'center',
          minWidth: '120',
          defaultText: '--',
          isCustom: false,
        },
        {
          key: 'device_checkpoint_number',
          label: '测点编号',
          align: 'center',
          minWidth: '120',
          defaultText: '--',
          isCustom: false,
        },
      ],
      siteList: [],
      currentSiteId: '',
    };
  },
  watch: {
    deviceList: {
      handler(val, oldVal) {
        if (val && val.length > 0) {
          this.currentDeviceId = this.currentDeviceId || (val[0] && val[0].id
            ? val[0].id : this.currentDeviceId);
        } else {
          this.currentDeviceId = '';
        }
      }, immediate: true, deep: true,
    },
    currentDeviceId: {
      handler(val, oldVal) {
        if (val) {
          this.getDeviceMonitorList();
        } else {
          this.deviceSetList = [];
        }
      }, immediate: true, deep: true,
    },
    siteList: {
      handler(val, oldVal) {
        if (val && val.length > 0) {
          this.currentSiteId = this.currentSiteId || (val[0] && val[0].id
            ? val[0].id : this.currentSiteId);
        } else {
          this.currentSiteId = '';
        }
      }, immediate: true, deep: true,
    },
    currentSiteId: {
      handler(val, oldVal) {
        if (oldVal != undefined && (typeof val == "number" || (typeof val
          == "string" && !val))) {
          this.getDeviceMonitorList();
        } else {
          this.deviceSetList = [];
        }
      }, immediate: true, deep: true,
    },
    isSelectedSubRiverId: {
      handler(val, oldVal) {
        if (val) {
          // 显示站点监测信息tab栏，获取站点列表，初始赋值站点选择
          this.stateList[4].isShow = true;
          this.getSiteList();
        } else {
          // 隐藏站点监测信息tab栏，初始赋值站点选择为空
          this.stateList[4].isShow = false;
        }
      }, immediate: true, deep: true,
    },
  },
  computed: {
    isSelectedSubRiverId() {
      return (this.currentType != -1 && this.currentSubRiverId != -1);
    },
  },
  created() {
    this.getAllSelectList();
  },
  methods: {
    getAllSelectList() {
      let data = {};
      this.$apis.unity_monitor_set_all(data).then(res => {
        if (res.result == 0) {
          this.allDataList = res.data;
          let initStr = localStorage.getItem('currentMonitorListSelect');
          let initObj = initStr ? JSON.parse(initStr) : {};
          this.currentType = initObj.river_type || -1;
          let typeArr = [
            {
              id: -1,
              name: '全局',
            },
          ];
          for (let i = 0; i < this.allDataList.length; i++) {
            let t = this.allDataList[i];
            typeArr.push({
              id: t.id,
              name: t.name,
            });
            if (this.currentType == t.id) {
              this.currentTypeIndex = i + 1;
            }
          }
          this.typeList = typeArr;

          this.currentState = initObj.real_type || 1;
          for (let i = 0; i < this.stateList.length; i++) {
            if (this.stateList[i].id == this.currentState) {
              this.currentStateIndex = i;
            }
          }
          this.currentSubRiverId = initObj.river_id || -1;
          if (this.currentState == 4) {
            this.currentDeviceId = initObj.device_id || '';
          } else if (this.currentState == 5) {
            this.currentSiteId = initObj.device_id || '';
          }
          if (this.currentState != 4 && this.currentState != 5) {
            this.getListPage();
          }
        }
      });
    },
    handleRiverTypeClick(item, index) {
      // 选择全局/河流/水库/坑塘
      this.datalist = []; // 置空测点列表
      this.currentType = item.id;
      this.currentTypeIndex = index;
      this.currentSubRiverId = -1;
      this.currentDeviceId = '';
      this.currentSiteId = '';
      this.deviceSetList = [];
      this.currentState = 1;
      if (this.currentType == -1) {
        this.getListPage();
      }

      this.resetStorageCurrentSelect();
    },
    handleSubRiverListClick(item) {
      // 选择对应的河流/水库/坑塘的id
      this.datalist = [];
      this.currentSubRiverId = item.id;
      this.currentDeviceId = '';
      this.currentSiteId = '';
      this.deviceSetList = [];
      this.currentState = 1;
      this.getListPage();

      this.resetStorageCurrentSelect(item);
    },
    handleStateClick(item) {
      // 选择实时状态1、实时监测2、安全监测3
      this.datalist = [];
      this.currentState = item.id;
      this.currentStateIndex = this.getStateIndexById(this.currentState);

      // if (this.currentState == 4) {
      // 设备
      // this.currentDeviceId = '';
      // this.getDeviceList();
      // } else if (this.currentState == 5) {
      // // 站点
      // this.currentSiteId = '';
      // this.getSiteList();
      // } else {
      this.getListPage();
      // }

      this.resetStorageCurrentSelect();
    },
    resetStorageCurrentSelect(item = null) {
      let params = {
        river_type: this.currentType,
        real_type: this.currentState,
        river_id: this.currentSubRiverId,
        device_id: this.currentState == 4 ? this.currentDeviceId
          : (this.currentState == 5 ? this.currentSiteId : ''),
        item: item,
      };
      localStorage.setItem('currentMonitorListSelect',
        JSON.stringify(params));
    },
    /**
     * 根据state值获取其在stateList中的index值
     * @param id
     * @return {number}
     */
    getStateIndexById(id) {
      let index = this.currentStateIndex;
      for (let i = 0; i < this.stateList.length; i++) {
        if (this.stateList[i].id == id) {
          index = i;
        }
      }
      return index;
    },
    //跳转新增
    navtoAdd(type, item = null) {
      localStorage.setItem('page', this.page)
      let queryObj = {
        type: type,
        river_type: this.currentType,
        river_id: this.currentSubRiverId,
        real_type: this.currentState,
      };
      if (type != 'add') {
        Object.assign(queryObj, {
          data: item,
        })
      }
      if (this.currentType != -1 && this.currentSubRiverId == -1) {
        Message.warning(
          '请选择' + this.allDataList[this.currentTypeIndex - 1].name);
        return;
      }

      this.resetStorageCurrentSelect(item);
      let url = '/admin/monitor/add';
      this.$router.push({
        path: url,
        query: queryObj,
      });
    },
    //删除
    del(item) {
      this.$confirm('确定要【' + item.name + '】分组的数据吗？删除后无法撤回。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {
          id: item.id
        }
        this.$apis.unity_monitor_set_del(data).then((res) => {
          if (res.result == 0) {
            this.getListPage();
          }
        });
      }).catch(() => {
      });
    },
    //查询分组列表
    getListPage() {
      let data = {
        river_type: this.currentType,
        real_type: this.currentState,
        river_id: this.currentSubRiverId,
      }
      if (this.currentType != -1 && this.currentSubRiverId == -1) {
        Message.warning(
          '请选择' + this.allDataList[this.currentTypeIndex - 1].name);
        return;
      }
      this.$apis.unity_monitor_set_list(data).then(res => {
        if (res.result == 0) {
          this.datalist = res.data
        }
      });
    },
    // 查询设备测点列表
    getDeviceList() {
      let list = [];
      if (this.currentSubRiverId != -1) {
        let parentList = this.allDataList[this.currentTypeIndex - 1]
        && this.allDataList[this.currentTypeIndex - 1].children
          ? this.allDataList[this.currentTypeIndex - 1].children : [];
        for (let i = 0; i < parentList.length; i++) {
          if (parentList[i].id == this.currentSubRiverId) {
            list = parentList[i].children || [];
          }
        }
      }
      this.deviceList = list;
    },
    getSiteList() {
      let data = {
        has_engine: 1, // -1 全部 0 按工程查询(10 水系联通工程……) 1 按地区查询(1 河流 2 水库 3 坑塘 4 灌区 5 其他)
        type: this.currentType,
        id: this.currentSubRiverId,
      };
      this.$apis.v2_safe_list(data).then(res => {
        if (res.result == 0) {
          let resData = res.data || [];
          this.siteList = resData;
        }
      }).catch((err) => {
        this.siteList = [];
      });
    },
    getDeviceMonitorList() {
      this.deviceSetList = [];
      let data = {
        river_type: this.currentType,
        river_id: this.currentSubRiverId,
      };
      // if (this.currentState == 4) {
      //   // 设备
      //   Object.assign(data, {
      //     equipment: this.currentDeviceId,
      //   });
      //   this.$apis.unity_monitor_device_list(data).then(res => {
      //     if (res.result == 0) {
      //       let resData = res.data || {};
      //       this.currentDeviceUpdateType = resData.hasOwnProperty(
      //         'is_default')
      //       && resData.is_default ? 'add' : 'update';
      //       this.deviceSetList = resData.data
      //     }
      //   });
      // } else if (this.currentState == 5) {
      //   // 站点
      //   Object.assign(data, {
      //     id: this.currentSiteId,
      //   });
      //   if (data.id == '') {
      //     return;
      //   }
      //   this.$apis.v2_safe_config_query(data).then(res => {
      //     if (res.result == 0) {
      //       let resData = res.data || [];
      //       this.deviceSetList = resData;
      //     }
      //   });
      // }
    },
    tipLookMonitorList(item) {
      let queryObj = {
        data: item,
      };
      this.resetStorageCurrentSelect(item);
      this.$router.push({
        path: '/admin/monitor/group',
        query: queryObj,
      });
    },
    updateDeviceSetting() {
      let dId = this.currentState == 4 ? this.currentDeviceId
        : (this.currentState == 5 ? this.currentSiteId : '');
      let dList = [];
      if (this.currentState == 4) {
        dList = this.currentDeviceUpdateType == 'add' ? []
          : this.deviceSetList;
      } else if (this.currentState == 5) {
        dList = this.deviceSetList;
      }

      let queryObj = {
        river_type: this.currentType,
        real_type: this.currentState,
        river_id: this.currentSubRiverId,
        device_id: this.currentState == 4 ? this.currentDeviceId
          : (this.currentState == 5 ? this.currentSiteId : ''),
        type: this.currentDeviceUpdateType,
        device_list: dList,
      };
      // if (this.currentState==4){
      //   // 设备
      //   Object.assign(queryObj,{
      //     device_list: this.currentDeviceUpdateType == 'add' ? []
      //       : this.deviceSetList,
      //   });
      // }else if (this.currentState==5){
      //   // 站点
      // }

      this.resetStorageCurrentSelect();
      this.$router.push({
        path: '/admin/monitor/add_device',
        query: queryObj,
      });
    },
    resetDeviceSetting() {
      let params = {};
      // if (this.currentState == 4) {
      //   // 设备
      //   Object.assign(params, {
      //     equipment: this.currentDeviceId,
      //   });
      //   this.$apis.unity_monitor_device_reset(params).then(res => {
      //     if (res.result == 0) {
      //       Message.success('重置成功');
      //       this.getDeviceMonitorList();
      //     }
      //   });
      // } else if (this.currentState == 5) {
      //   // 站点 重置
      // }
    },
  }
};
</script>

<style>
</style>
